(function(window){//缩水版jquery

	function jquery(selector){
		return new jquery.fn.init(selector);
	}

	jquery.fn = jquery.prototype = {
		constructor: jquery,
		elements: null,
		init: function(selector){
			this.elements = document.getElementById(selector);
			return this;
		},
		on: function(type, fn, self,origin){
			if(this.elements.addEventListener){
				this.elements.addEventListener(type, function(e){
					fn.call(self, e, origin);
				},false);
			}
			else if(this.elements.attachEvent){
				this.elements.attachEvent('on'+type, function(e){
					fn.call(self, e, origin);
				});
			}
			else{
				this.elements['on'+type] = function(e){
					fn.call(self, e, origin);
				};
			}
		}
	};


	jquery.fn.init.prototype = jquery.fn;

	window.$ = jquery;
})(window);




(function(window){//页面主逻辑

var like = {
	tag:  		$('tag').elements,
	tagShow: 	{start:$('tag').elements, end:$('tagShow').elements, metadata: []},
	text: 		$('text').elements,
	btn: 			$('btn').elements,
	wrap: 		{start: text, end: $('wrap').elements, metadata: []},
	tagLen:   10,
	flag: 		false,
	regSeparator: new RegExp(/[\s\n\.\-。,，、]+/,'igm'),
	regSeparator1: new RegExp(/(^[\s\n\.\-。,，、]*)|([\s\n\.\-。,，、]*$)/,'igm'),
	keyUp: function(e) {
    this.valiadation(this.tagShow);
    this.render(this.tagShow);
  },
  valiadation: function(origin){
  	var obj = {}, arr = [], arr2 = [], temp = origin.start.value.trim();
  	if(temp){
  		this.flag = true;
  		//分割为数组
  		temp = temp.replace(this.regSeparator1,'').replace(this.regSeparator,'|').split('|');
  		//去除重复的
  		for(var i = 0; i < temp.length; i++){
  			obj[temp[i]] = i;
  		}
  		for(key in obj){
  			arr.push(key);
  		}

  		
  		if(arr.length > this.tagLen){//多余10个时去除前面的留10个
  			for(i = 0; i < this.tagLen; i++){
  		
  				arr2.push(arr[arr.length - this.tagLen + i]);
  			}
  			origin.metadata = arr2;
  		}else{
  			origin.metadata = arr;
  		}
  		
  	}else{
  		this.flag = false; 
  	}
  },
  btnClick: function(){
  	this.valiadation(this.wrap);
    this.render(this.wrap);
  },
  remove: function(e, origin){
  	var e = e || window.event;
  	if(e.target.nodeName.toLowerCase() === 'span'){
  		this.flad = true;
  		for(var i in origin.metadata){
  			if(origin.metadata[i] == e.target.innerHTML){
  				origin.metadata.splice(i,1);
  			}
  		}
  		
  		this.render(origin);
  	}
  },
  //渲染数据
  render: function(control){

  	if(!this.flag)return;

  	var temp = '';
  	for(var i in control.metadata){
  		temp += '<span>' + control.metadata[i] + '</span>';
  	}
  	control.end.innerHTML = temp;
  },
  init: function(){
  	$('tag').on('keyup', this.keyUp, this);
  	$('btn').on('click',this.btnClick, this);
  	$('tagShow').on('click', this.remove, this, this.tagShow);
  	$('wrap').on('click', this.remove, this, this.wrap);
  }
};

window.like = like;

})(window);


like.init();